package cn.jdy.plugins.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Doc;

/**
 * 营销智库服务类
 * Created by Tianyi on 2014/7/10.
 */
@Service
@Transactional
public class DocService extends BaseDao<Doc> {

	@Autowired
	private ConfService confService;

	/**
	 * 按条件查询
	 *
	 * @param entity
	 * @return
	 */
	public List<Doc> query(Doc entity, String... date) {
		if(entity == null) return super.findAll();
		if(entity.getColumnId()!=null) {
			StringBuilder sbd = new StringBuilder();
			List<ConfValue> list = confService.queryByType(GlobalConstant.TYPE_DOC, entity.getColumnId());
			//如果有字元素，则采用SQL查询
			if(list!=null && list.size()>0) {
			  List<Long> listArray = new ArrayList<Long>();
			  listArray.add(entity.getColumnId());
				for(ConfValue cv : list) {
					listArray.add(cv.getId());
				}
				DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
        dc.add(Restrictions.eq("status", entity.getStatus()));
        dc.add(Restrictions.in("columnId", listArray.toArray()));
        dc.addOrder(Order.desc("createTime"));
        return super.find(dc,entity.getiDisplayStart(),entity.getiDisplayLength());
			}else {
				return super.find(createFilter(entity, date),
				    entity.getiDisplayStart(),entity.getiDisplayLength());
			}
		}else {
			return super.find(createFilter(entity, date),
			    entity.getiDisplayStart(),entity.getiDisplayLength());
		}
	}

	/**
	 * 查询记录数
	 *
	 * @param entity
	 * @return
	 */
	public Long count(Doc entity, String... date) {
		if(entity.getColumnId()!=null) {
			StringBuilder sbd = new StringBuilder();
			List<ConfValue> list = confService.queryByType(GlobalConstant.TYPE_DOC, entity.getColumnId());
			//如果有字元素，则采用SQL查询。 Filter.find.in可以用以后， 删除此处,转移到createFilter。
			if(list!=null && list.size()>0) {
			  List<Long> listArray = new ArrayList<Long>();
        listArray.add(entity.getColumnId());
        for(ConfValue cv : list) {
          listArray.add(cv.getId());
        }
				DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
				dc.add(Restrictions.eq("status", entity.getStatus()));
				dc.add(Restrictions.in("columnId", listArray.toArray()));
				return super.count(dc);
			}else {
				return super.count(createFilter(entity, date));
			}
		}else {
			return super.count(createFilter(entity, date));
		}

	}

	/**
	 * 拼装条件
	 *
	 * @param entity
	 * @param page
	 * @return
	 */
	private DetachedCriteria createFilter(Doc entity, String... date) {
	  DetachedCriteria filter = DetachedCriteria.forClass(entityClass);
		if(entity.getKeyword() != null) {
			if(entity.getKeyword().trim().length() > 0) {
				filter.add(Restrictions.like("title", "%"+entity.getKeyword().trim()+"%"));
			}
		}
		if(StringUtil.isNotEmpty(entity.getStatus())){
		  filter.add(Restrictions.eq("status", entity.getStatus()));
		}
		if(StringUtil.isNotEmpty(entity.getUserId())){
		  filter.add(Restrictions.eq("userId", entity.getUserId()));
		}
		if(entity.getColumnId() != null){
		  filter.add(Restrictions.eq("columnId", entity.getColumnId()));
		}
		if(StringUtil.isNotEmpty(entity.getKeywords())){
		  if(StringUtil.isNotEmpty(entity.getKeyType())){
		    filter.add(Restrictions.like("keyType", "%"+entity.getKeywords().trim()+"%"));
		  }else{
		    //需要增加模糊搜索
		  }
		}
		if(date.length>0 && date[0]!=null && date[1]!=null && date[0].length()>0 && date[1].length()>0){
		  filter.add(Restrictions.between("createTime", date[0], date[1]));
		}
		filter.addOrder(Order.desc("createTime"));
		return filter;
	}

	/**
	 * 按照类型查询 文章
	 *
	 * @return
	 */
	public List<Doc> findByType(long columnId) {
	  DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
	  dc.add(Restrictions.eq("cv.id", columnId));
	  dc.add(Restrictions.eq("status", "1"));
	  dc.addOrder(Order.desc("createTime"));
		return super.find(dc);
	}

	/**
	 * 查询排行榜
	 *
	 * @param topType: 排序类型（字段名）
	 * @param isAsc:   排序规则（true 顺序, false 逆序）
	 * @return
	 */
	public List<Doc> queryTops(String topType, boolean isAsc) {
		DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
    dc.add(Restrictions.eq("status", "1"));
    if(isAsc){
      dc.addOrder(Order.asc(topType));
    }
    return super.find(dc,0,10);
	}

	/**
	 * 增加一次 访问量、点赞量、下载次数
	 *
	 * @param id
	 * @param type
	 */
	public void addOneTime(long id, char type) {
		try {
			Doc doc = super.find(id);
			if(doc == null) return;
			switch(type) {
				case 'r':
					doc.setReadTimes(doc.getReadTimes() + 1);
					break;
				case 'g':
					doc.setGoodTimes(doc.getGoodTimes() + 1);
					break;
				case 'd':
					doc.setDownTimes(doc.getDownTimes() + 1);
					break;
				default:
					return;
			}
			super.update(doc);
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "addOneTime", e);
		}
	}

}
